<template>
  <a-card :bordered="false">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <a-button v-auth="[1, 2]" type="primary" style="margin: 0 10px" @click="openAddPopup">創建比賽</a-button>
      </a-col>
    </a-row>
    <div ref="crudContentRef">
      <a-table
        :loading="loading"
        :scroll="{ x: '100%', y: '100%' }"
        :columns="columns"
        :pagination="false"
        :data="data">
        <template #optional="{ record }">
          <a-link v-auth="[1, 2]" @click="openEditPopup(record)"> 查看賽程 </a-link>
          <a-popconfirm v-if="false" content="確定刪除嗎？" @before-ok="deleteBanner(record)" type="warning">
            <a-link v-auth="[1, 2]" status="danger"> 刪除 </a-link>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <a-modal
      v-model:visible="visible"
      :title="type == 'add' ? '添加' : '編輯'"
      width="600px"
      :ok-loading="btnLoading"
      @cancel="close"
      @before-ok="submit">
      <a-form ref="formRef" :model="formData" :rules="rules" :auto-label-width="true">
        <a-form-item label="比賽名稱" field="name">
          <a-input v-model="formData.name" placeholder="請輸入比賽名稱" />
        </a-form-item>
        <a-form-item label="描述" field="description">
          <a-input v-model="formData.description" placeholder="請輸入比賽描述" />
        </a-form-item>
        <a-form-item label="比賽時間" field="timeList">
          <a-range-picker
            v-model="formData.timeList"
            showTime
            :time-picker-props="{
              defaultValue: ['00:00:00', '00:00:00'],
            }"
            @change="onChange"
            style="width: 100%" />
        </a-form-item>
      </a-form>
      *創建完成後不可修改
    </a-modal>
    <Schedul ref="schedul" />
  </a-card>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import tournamentApi from '@/api/tournament'
import { Message } from '@arco-design/web-vue'
import Schedul from '@/components/Schedul/index.vue'
const schedul = ref(null)
const openEditPopup = async (record) => {
  loading.value = true
  await schedul.value.open(record)
  loading.value = false
}

const type = ref('add')
const visible = ref(false)
const btnLoading = ref(false)
const formRef = ref(null)
const formData = ref({
  name: '',
  description: '',
  start_time: '',
  end_time: '',
  timeList: [],
})
const rules = [
  {
    name: [{ required: true, message: '請輸入比賽名稱' }],
    description: [{ required: true, message: '請輸入比賽描述' }],
    timeList: [{ required: true, message: '請選擇比賽時間' }],
  },
]
const openAddPopup = () => {
  type.value = 'add'
  formData.value = {
    name: '',
    description: '',
    start_time: '',
    end_time: '',
    timeList: [],
  }
  visible.value = true
}
const close = () => {
  visible.value = false
  btnLoading.value = false
}
const submit = async (done) => {
  const validate = await formRef.value?.validate()
  if (validate) return done(false)
  if (type.value === 'add') {
    try {
      await tournamentApi.createTournament({
        name: formData.value.name,
        description: formData.value.description,
        start_time: formData.value.start_time,
        end_time: formData.value.end_time,
      })
      close()
      Message.success(`添加成功！`)
      init()
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  } else {
    try {
      // await tournamentApi.updateTournament(formData.value)
      close()
      Message.success(`修改成功！`)
      init()
    } catch (error) {
      btnLoading.value = false
      done(false)
    }
  }
}
const onChange = (dateString) => {
  if (dateString) {
    formData.value.start_time = dateString[0]
    formData.value.end_time = dateString[1]
  } else {
    formData.value.start_time = ''
    formData.value.end_time = ''
  }
}

const columns = ref([
  {
    title: '比賽名稱',
    dataIndex: 'name',
  },
  {
    title: '描述',
    dataIndex: 'description',
    ellipsis: true,
  },
  {
    title: '比賽開始時間',
    dataIndex: 'start_time',
    width: 170,
  },
  {
    title: '比賽結束時間',
    dataIndex: 'end_time',
    width: 170,
  },
  {
    title: '創建時間',
    dataIndex: 'ctime',
    width: 170,
  },
  {
    title: '操作',
    slotName: 'optional',
    width: 170,
  },
])
const data = ref([])

const loading = ref(false)
const init = async () => {
  loading.value = true
  try {
    const res = await tournamentApi.getTournamentList({})
    loading.value = false
    data.value = res.data
  } catch (error) {
    loading.value = false
  }
}
init()

const crudContentRef = ref(null)
onMounted(async () => {
  await nextTick(() => {
    window.addEventListener('resize', settingFixedPage, false)
    settingFixedPage()
  })
})
const settingFixedPage = () => {
  const workAreaHeight = document.querySelector('.work-area').offsetHeight
  let tableHeight = workAreaHeight - 24 - 32 - 8 - 24
  if (crudContentRef.value) {
    if (crudContentRef.value) {
      crudContentRef.value.style.height = tableHeight + 'px'
    }
  }
}
</script>
